import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {AppConfig} from '../config';
import {Capacity} from '../entity/capacity.model';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class CapacityViewService {
  private param = 'rPowers';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(
    private http: InterceptorService,
  ) {
  }

  // date = '2017-05-01' 各风场当月电量;date='',各风场全年电量
  getMonthPowers(date: any): Promise<Capacity[]> {
    let resqustUrl = `${this.url}/date/${date}`;
    return this.http.get(resqustUrl)
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data as Capacity[];
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }

  // farmId = 0是公司全年，!=0是风场全年（12个月的电量指标）
  getYearPowers(farmId: number): Promise<Capacity[]> {
    let resqustUrl = `${this.url}/farmId/${farmId}`;
    return this.http.get(resqustUrl)
      .toPromise()
      .then(response => {
        let resault = response;
        try {
          switch (resault.code) {
            case '200':
              return resault.data as Capacity[];
            case '-1':
              throw new Error(resault.message);
          }
        }
        catch (error) {
          throw error;
        }
      })
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }
}
